package com.qf.medicaldoctoradmin.healthMonitor.monitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.common.entity.Monitor;
import com.qf.common.utils.CopyNotNullUtils;
import com.qf.common.utils.UserUtils;
import com.qf.medicaldoctoradmin.healthMonitor.monitor.dao.MonitorDao;
import com.qf.medicaldoctoradmin.healthMonitor.monitor.service.MonitorService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class MonitorServiceImpl implements MonitorService {
    @Resource
    private MonitorDao monitorDao;


    @Override
    public Monitor selectOne() {
        Integer uid = UserUtils.getUid();
        Monitor monitor = monitorDao.selectOne(new LambdaQueryWrapper<Monitor>()
                .eq(Monitor::getPatientId, uid)
                .last("LIMIT 1")
                .orderByDesc(Monitor::getMonitorDate));
        if (monitor == null) {
            throw new RuntimeException("空空如也");
        }
        return monitor;
    }

    @Override
    public List<Monitor> selectList() {
        Integer uid = UserUtils.getUid();
        List<Monitor> monitors = monitorDao.selectList(new LambdaQueryWrapper<Monitor>()
                .eq(Monitor::getPatientId, uid));
        if (monitors == null) {
            throw new RuntimeException("空空如也");
        }
        return monitors;
    }

    @Override
    public void updateOneInfo(Monitor monitor) {
        if (monitor == null) {
            throw new RuntimeException("请先输入更新数据");
        }

        // 先根据id获取唯一的健康数据对象
        Monitor monitorOptional = monitorDao.selectOne(new LambdaQueryWrapper<Monitor>()
                .eq(Monitor::getId, monitor.getId()));

        // 更新字段
        try {
            CopyNotNullUtils.copyNonNullProperties(monitorOptional, monitor);
            monitor.setMonitorDate(new Date());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        monitorDao.updateById(monitor);


    }

    @Override
    public void delete(Monitor monitor) {
        if (monitor.getId() == null) {
            throw new RuntimeException("请先选择一个记录再进行删除");
        }
        monitorDao.deleteById(monitor);
    }

}
